package com.adgroup.doremon_ad;

import java.text.SimpleDateFormat;
import java.util.Date;

import model.User;

import org.json.JSONException;
import org.json.JSONObject;

import util.Config;
import util.Utility;
import adapter.JsonParse;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import database.Database;

public class RegisterActivity extends SherlockFragmentActivity{

	private DisplayMetrics metrics;
	private LinearLayout menuPanel;
	private int panelWidth;
	private LinearLayout slidingPanel;
	private boolean isExpanded;
  
	FrameLayout.LayoutParams menuPanelParameters;
	FrameLayout.LayoutParams slidingPanelParameters;
	LinearLayout.LayoutParams headerPanelParameters; 
	LinearLayout.LayoutParams listViewParameters; 
	
	RelativeLayout.LayoutParams lvcategoriesParameters;
	
	//views
	Button btnAvatar;
	EditText etgmail;
	EditText etnickname;
	EditText etPass;
	EditText etRePass;
	EditText etUsername;
	CheckBox chkMale;
	CheckBox chkFemale;
	TextView tvBirthday;
	StringBuilder sBirthday;
	LinearLayout linearRoot;
	ImageButton btnBirthday;
	Button btnRegister;
	Spinner spinner;
	ProgressBar progressWaiting;
	ImageView ivAvatar;
	
	private int mYear;
	private int mMonth;
	private int mDay;
	private int logoid = 0;
	private String gcmId = "";
	private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
	ProgressDialog progress;
	Handler handler = new Handler();
	LinearLayout root;
	
	
	private ActionBar mActionBar;
	private View v;
	int page = 1;
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
		case android.R.id.title:
			finish();
			break;		
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	/*private StartAppAd startAppAd = new StartAppAd(this); 
	@Override 
	public void onResume(){ 
	      super.onResume(); 
	      startAppAd.onResume(); 
	  } 
	@Override 
	  public void onPause() { 
	      super.onPause(); 
	      startAppAd.onPause(); 
	  } 
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if(keyCode==KeyEvent.KEYCODE_HOME){
			 startAppAd.showAd(); 
			    startAppAd.loadAd(); 
		}
		return super.onKeyDown(keyCode, event);
	}*/
	@SuppressLint({ "CutPasteId", "NewApi" })
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.register);
		
		 AdView mAdView = (AdView) this.findViewById(R.id.adView);
		    AdRequest adRequest = new AdRequest.Builder().build();
		    mAdView.loadAd(adRequest);
		    
		//action bar
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(false);
		mActionBar.setDisplayUseLogoEnabled(true);
		mActionBar.setHomeButtonEnabled(true);
		mActionBar.setTitle(getResources().getString(R.string.buttonregister));
		mActionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_actionbar));
		
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		
		//set up
		panelWidth = (int) ((metrics.widthPixels) * 0.6);
		menuPanel = (LinearLayout) findViewById(R.id.menuPanelRegister);
		menuPanelParameters = (FrameLayout.LayoutParams) menuPanel
				.getLayoutParams();
		menuPanelParameters.width = panelWidth;
		menuPanel.setLayoutParams(menuPanelParameters);
		slidingPanel = (LinearLayout) findViewById(R.id.slidemainregister);
		slidingPanelParameters = (FrameLayout.LayoutParams) slidingPanel
				.getLayoutParams();
		slidingPanelParameters.width = metrics.widthPixels;
		slidingPanel.setLayoutParams(slidingPanelParameters);

		
		//mapping
		tvBirthday = (TextView) findViewById(R.id.txtbirthdayfill);
		etUsername = (EditText) findViewById(R.id.editTextUserName);
		chkFemale = (CheckBox) findViewById(R.id.checkfemale);
		chkMale = (CheckBox) findViewById(R.id.checkmale);
		etgmail = (EditText) findViewById(R.id.editTextGmail);
		etnickname = (EditText) findViewById(R.id.editTextNickName);
		etPass = (EditText) findViewById(R.id.editTextPassword);
		etRePass = (EditText) findViewById(R.id.editTextRePassWord);
		linearRoot = (LinearLayout) findViewById(R.id.slidemainregister);
		btnBirthday = (ImageButton) findViewById(R.id.btnbirthday);
		btnRegister = (Button) findViewById(R.id.btnregister);
		spinner = (Spinner) findViewById(R.id.spinneruserlogo);
		progressWaiting =(ProgressBar) findViewById(R.id.progressBarwaitinguserlogo);
		
		root = (LinearLayout) findViewById(R.id.rootregister);
		
		//set adapter
		root.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				try {
					imm.hideSoftInputFromWindow(etgmail.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etPass.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etRePass.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etnickname.getWindowToken(), 0);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		});
		//set male
		chkMale.setChecked(true);
		//load logo
		

		//register gcm id
		//new AsynGetGCMID().execute();
		
		//GCMRegistrar.checkDevice(this);
		/*GCMRegistrar.checkManifest(this);
		// Get GCM registration id
		gcmId = GCMRegistrar.getRegistrationId(this);
		GCMRegistrar.setRegisterOnServerLifespan(getApplicationContext(),
				604800000);	 
		if (gcmId.equals("")) {
			GCMRegistrar.register(this, Configuration.SENDERID);
		} else {
			long limittime = GCMRegistrar.getRegisterOnServerLifespan(this);
		
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skip Register;
			} else {
				GCMRegistrar.register(this, Configuration.SENDERID);
			}
		}
		//broadcast to receive gcm id
		BroadcastReceiver receiverRefresh = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String yourData = intent.getStringExtra("regid");
				if (yourData != null) {
					gcmId = yourData;
					GCMRegistrar.setRegisteredOnServer(context, true);
				}

			}
		};*/
		
		//
		etgmail.setCursorVisible(true);
		etgmail.setFocusable(true);
		etgmail.setFocusableInTouchMode(true);
		ShowKeyboard(etgmail);
		mYear = 1991;
		mMonth = 11;
		mDay = 1;
		updateBirthday();
		btnBirthday.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				DatePickerDialog DPD = new DatePickerDialog(RegisterActivity.this,dateSetListener, mYear, mMonth, mDay);
				DPD.show();	
				updateBirthday();
			}
		});
		chkMale.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1){
					chkFemale.setChecked(false);
				}
				else{
					chkFemale.setChecked(true);
				}
			}
		});
		chkFemale.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1){
					chkMale.setChecked(false);
				}
				else{
					chkMale.setChecked(true);
				}
			}
		});
		
		//register
		btnRegister.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				try {
					imm.hideSoftInputFromWindow(etgmail.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etPass.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etRePass.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etnickname.getWindowToken(), 0);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
				String  gmail = etgmail.getText().toString();
				String  username = etUsername.getText().toString();
				String nickname = etnickname.getText().toString();
				String pass = (etPass.getText().toString());
				String retype = (etRePass.getText().toString());
				boolean isEmail = Utility.isEmailValid(gmail);
				StringBuilder birthday = new StringBuilder().append(mYear).append("-").append(mMonth + 1).append("-").append(mDay);
				String isGender;
				Date now = new Date();
				Integer checkYear = mYear - Integer.parseInt(formatter.format(now));

				if(chkFemale.isChecked()){
					isGender = "0";
				}
				else{
					isGender = "1";
				}
				
				//check infor
				if(gmail.equalsIgnoreCase("")){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.errornullgmailregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etgmail, true);
								}
					}).show();
				}
				else if(!isEmail){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.errorninvalidgmailregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etgmail, true);
								}
					}).show();
				}
			/*	else if(username.equalsIgnoreCase("")){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.errornullusernameregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etUsername, true);
								}
					}).show();
				}
				else if(username.length()<6){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.error6usernameregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etUsername, true);
								}
					}).show();
				}*/
				else if(nickname.equalsIgnoreCase("")){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.errornullnicknameregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etnickname, true);
								}
					}).show();
				}
				else if(nickname.length()<6){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.error6nicknameregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etnickname, true);
								}
					}).show();
				}
				else if(pass.equalsIgnoreCase("")){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.errornullpassregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etPass, true);
								}
					}).show();
				}
				else if(pass.length()<6){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.error6passregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etPass, true);
								}
					}).show();
				}
				else if(retype.equalsIgnoreCase("")){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.errornullrepassregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etRePass, true);
								}
					}).show();
				}
				else if(!retype.equalsIgnoreCase(pass)){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.errormatchespassregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etRePass, true);
								}
					}).show();
				}
				else if(checkYear>-5){
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.errortitleregister))
					.setMessage(getResources().getString(R.string.errorbirthdayregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									DatePickerDialog DPD = new DatePickerDialog(RegisterActivity.this,dateSetListener, mYear, mMonth, mDay);
									DPD.show();										
								}
					}).show();
				}
				else {
					if(!Utility.isConnect(RegisterActivity.this)){
						new AlertDialog.Builder(RegisterActivity.this)
						.setTitle(getResources().getString(R.string.titleerrornetwork))
						.setMessage(getResources().getString(R.string.messageerrornetwork))
						.setNegativeButton(getResources().getString(R.string.setting), new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								
							}
						})
						.setPositiveButton(getResources().getString(R.string.cancel),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
									}
						}).show();
					}
					else{
						pass = Utility.md5(pass);
						retype = Utility.md5(retype);
						String[] params = new String[] {gmail,username,nickname,pass,isGender+"",mYear+"-"+mMonth+"-"+mDay,"1","1",gcmId};
						Log.d("json", "asd");
						new AsynRegister().execute(params);//gmail,username,nickname,pass,isGender+"",mYear+"-"+mMonth+"-"+mDay,"Platform",gcmId
					}
				}				
			}
		});
	}
	
	@Override
	public void onConfigurationChanged(
			android.content.res.Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
		int orientation = newConfig.orientation;
		if(orientation==android.content.res.Configuration.ORIENTATION_PORTRAIT){
			//set up
			panelWidth = (int) ((metrics.widthPixels) * 0.6);			
			menuPanelParameters = (FrameLayout.LayoutParams) menuPanel
					.getLayoutParams();
			menuPanelParameters.width = panelWidth;
			menuPanel.setLayoutParams(menuPanelParameters);
			
			slidingPanelParameters = (FrameLayout.LayoutParams) slidingPanel
					.getLayoutParams();
			slidingPanelParameters.width = metrics.widthPixels;
			slidingPanel.setLayoutParams(slidingPanelParameters);

		} 
		else if(orientation==android.content.res.Configuration.ORIENTATION_LANDSCAPE){
			panelWidth = (int) ((metrics.heightPixels) * 0.6);			
			menuPanelParameters = (FrameLayout.LayoutParams) menuPanel
					.getLayoutParams();
			menuPanelParameters.width = panelWidth;
			menuPanel.setLayoutParams(menuPanelParameters);
			
			slidingPanelParameters = (FrameLayout.LayoutParams) slidingPanel
					.getLayoutParams();
			slidingPanelParameters.width = metrics.heightPixels;
			slidingPanel.setLayoutParams(slidingPanelParameters);
		}
	}

	//class load more search friend
	public class EndlessScrollListener implements OnScrollListener {

		private int visibleThreshold;
		private int previousTotal;
		private boolean loading;

		public EndlessScrollListener() {
			visibleThreshold = 1;
			previousTotal = 0;
			loading = true;
		}

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (loading) {
				if (totalItemCount > previousTotal) {
					loading = false;
					previousTotal = totalItemCount;			
				}
			}
			if (!loading
					&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
				
				loading = true;
			}			
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

	}
	public void setEditTextFocus(EditText et, boolean isFocused)
	{
		et.setCursorVisible(isFocused);
		et.setFocusable(isFocused);
		et.setFocusableInTouchMode(isFocused);

	    if (isFocused) 
	    {
	    	et.requestFocus();
	    }
	    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
	}
	//show keyboard
	public void ShowKeyboard(EditText et)
	{
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
	}
	//
	protected void updateBirthday() {
		tvBirthday.setText(new StringBuilder()
				.append(mDay).append("-").append(mMonth + 1).append("-")
				.append(mYear));
	}
	private OnDateSetListener dateSetListener = new OnDateSetListener() {
		
		@Override
		public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
			mYear = arg1;
			mMonth = arg2;
			mDay = arg3;
			updateBirthday();
		}
	};
	
	
	//asyntask regisster
	class AsynRegister extends AsyncTask<String, Void, String>
	{ 
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(RegisterActivity.this, "",
					getResources().getString(R.string.registering), true);
		}
		@Override
		protected String doInBackground(String... params) {
			return JsonParse.getInstance().registerAccount(params,RegisterActivity.this);
		}
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progress.dismiss();
			JSONObject json;
			try {
				json = new JSONObject(result);
				String res = json.getString(Config.result);
				if(res.equalsIgnoreCase("0")){
					Utility.ShowAlert(RegisterActivity.this, "", getResources().getString(R.string.errornexistgmailregister));
				}
				else if(res.equalsIgnoreCase("0")){
					Utility.ShowAlert(RegisterActivity.this, "", getResources().getString(R.string.errornexistusernameregister));
				}
				else{
					JSONObject rjson = json.getJSONArray(Config.result).getJSONObject(0);
					String gmai = rjson.getString(User.keyGmail);
					String nickname = rjson.getString(User.keyNickName);
					//String userName = rjson.getString(User.keyUserName);
					String birthday = rjson.getString(User.keyBirthday);
					String type = rjson.getString(User.keyType);
					String gender = rjson.getString(User.keyGender);
					String time = rjson.getString(User.keyTime);
					//String logo = rjson.getString(User.keyLogo);
					final String userid = rjson.getString(User.keyUserId);
					User u = new User(userid, "", nickname, gender, birthday, type, gmai, time,"");
					new Database(RegisterActivity.this).setUser(u);
					new AlertDialog.Builder(RegisterActivity.this)
					.setTitle(getResources().getString(R.string.successtitleregister))
					.setMessage(getResources().getString(R.string.successmessageregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									Intent returnIntent = new Intent();
									returnIntent.putExtra("result", etnickname.getText().toString());									
									setResult(RESULT_OK, returnIntent);
									finish();									
								}
					}).show();
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	//get gcm id
	/*class AsynGetGCMID extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected Void doInBackground(Void... params) {
			if(gcm==null){
				//GCMRegistrar.checkManifest(RegisterActivity.this);
				gcm = GoogleCloudMessaging.getInstance(RegisterActivity.this);
				try {
					gcmId = gcm.register(Configuration.SENDERID);
					Log.d("log","gcm:"+gcmId);
				} catch (IOException e) {
					gcmId = "";
					Log.e("error",e.getMessage());
				}
			}
			return null;
		}
		
	}*/
	
}
